var express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
// 定义数据库连接地址
const mongoUri = 'mongodb://localhost:27017/chatgpt';

// 创建数据库连接函数
const connectToDatabase = async () => {
  try {
    // 使用 Mongoose 连接 MongoDB 数据库
    await mongoose.connect(mongoUri, { useNewUrlParser: true, useUnifiedTopology: true });
    console.log('Connected to database!');
  } catch (err) {
    console.error(err.message);
    // 连接失败时，等待 5 秒钟后重新连接数据库
    setTimeout(connectToDatabase, 5000);
  }
};

// 调用数据库连接函数
connectToDatabase();
// 定义聊天历史数据模型
const chatHistorySchema = new mongoose.Schema({
  userId: { type: String, required: true },
  nickName: { type: String, required: false },
  userMessage: { type: String, required: true },
  chatGptResponse: { type: String, required: true },
  type: { type: String, required: true, default: '对话' },
  createdDate: { type: Date, default: Date.now },
  responseDate: { type: Date, default: Date.now },
});
// 创建聊天历史数据模型实例
const ChatHistory = mongoose.model('ChatHistory', chatHistorySchema);
// 创建路由来处理聊天历史记录请求
router.post('/chat-history', async (req, res) => {
  const { userId, nickName, userMessage, chatGptResponse, createdDate, responseDate, type } = req.body;
  // 将请求体中的聊天记录保存到数据库中
  try {
    const chatHistory = new ChatHistory({ userId, nickName, userMessage, chatGptResponse, createdDate, responseDate, type });
    await chatHistory.save();
    res.status(201).json({});
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

module.exports = router;
